#include "../head/HistoryForm.h"
#include "ui_historyform.h"
#include "../head/mainwindow.h"

HistoryForm::HistoryForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::HistoryForm)
{
    ui->setupUi(this);
    this->setWindowTitle("信号回放");
    //connect(nf_2, &HistoryForm::triggerRender, this,&HistoryForm_1::drawWaveformPlot);
    for (int i=0; i<EQ_ALL_ERR_LEN; i++)
    {
        x_1.append(i);
        y_1.append(mutiSignalDecode->EqSig_PriCh_Temp_I[HIGH][i]);
    }
    curGraph_1 = ui->customPlot_1->addGraph();
    curGraph_1->setLineStyle(QCPGraph::lsNone);
    curGraph_1->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 2));
    ui->customPlot_1->plotLayout()->insertRow(0);
    m_title_1 = new QCPTextElement(ui->customPlot_1, "Re");
    ui->customPlot_1->plotLayout()->addElement(0, 0, m_title_1);
    curGraph_1->setData(x_1, y_1);
    // 为坐标轴添加标签
    //ui->customPlot->xAxis->setLabel("In-Phase");
    //ui->customPlot->yAxis->setLabel("Quadrature");
    // 设置坐标轴的范围，以看到所有数据
    ui->customPlot_1->graph(0)->rescaleAxes();
    ui->customPlot_1->legend->setVisible(false); // 显示图例
    ui->customPlot_1->replot();

    for (int i=0; i<EQ_ALL_ERR_LEN; i++)
    {
        x_2.append(i);
        y_2.append(mutiSignalDecode->EqSig_PriCh_Temp_Q[HIGH][i]);
    }
    curGraph_2 = ui->customPlot_2->addGraph();
    curGraph_2->setLineStyle(QCPGraph::lsNone);
    curGraph_2->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 2));
    ui->customPlot_2->plotLayout()->insertRow(0);
    m_title_2 = new QCPTextElement(ui->customPlot_2, "Im");
    ui->customPlot_2->plotLayout()->addElement(0, 0, m_title_2);
    curGraph_2->setData(x_2, y_2);

    // 设置坐标轴的范围，以看到所有数据
    ui->customPlot_2->graph(0)->rescaleAxes();
    ui->customPlot_2->legend->setVisible(false); // 显示图例
    ui->customPlot_2->replot();

    for (int i=0; i<EQ_ALL_ERR_LEN; i++)
    {
        x_3.append(i);
        y_3.append(mutiSignalDecode->EqErr_PriCh_Temp[HIGH][i]);
    }
    curGraph_3 = ui->customPlot_3->addGraph();
    curGraph_3->setLineStyle(QCPGraph::lsLine);
    ui->customPlot_3->graph(0)->setPen(QPen(Qt::magenta)); // 曲线的颜色
    ui->customPlot_3->plotLayout()->insertRow(0);
    m_title_3 = new QCPTextElement(ui->customPlot_3, "均衡后误差");
    ui->customPlot_3->plotLayout()->addElement(0, 0, m_title_3);
    curGraph_3->setData(x_3, y_3);
    // 为坐标轴添加标签
    //ui->customPlot->xAxis->setLabel("In-Phase");
    //ui->customPlot->yAxis->setLabel("Quadrature");
    // 设置坐标轴的范围，以看到所有数据
    ui->customPlot_3->graph(0)->rescaleAxes();
    ui->customPlot_3->legend->setVisible(false); // 显示图例
    ui->customPlot_3->replot();

    for (int i=0; i<MseqCorrOut_PriCh_TempSize; i++)
    {
        x_4.append(i);
        y_4.append(mutiSignalDecode->MseqCorrOut_PriCh_Temp[HIGH][i]);
    }
    curGraph_4 = ui->customPlot_4->addGraph();
    curGraph_4->setLineStyle(QCPGraph::lsLine);
    ui->customPlot_4->graph(0)->setPen(QPen(Qt::magenta)); // 曲线的颜色
    ui->customPlot_4->plotLayout()->insertRow(0);
    m_title_4 = new QCPTextElement(ui->customPlot_4, "M序列相关");
    ui->customPlot_4->plotLayout()->addElement(0, 0, m_title_4);
    curGraph_4->setData(x_4, y_4);
    // 为坐标轴添加标签
    //ui->customPlot->xAxis->setLabel("In-Phase");
    //ui->customPlot->yAxis->setLabel("Quadrature");
    // 设置坐标轴的范围，以看到所有数据
    ui->customPlot_4->graph(0)->rescaleAxes();
    ui->customPlot_4->legend->setVisible(false); // 显示图例
    ui->customPlot_4->replot();


    for (int i=0; i<EQ_ALL_ERR_LEN; i++)
    {
        x_5.append(i);
        y_5.append(mutiSignalDecode->EqSig_PriCh_Temp_I[LOW][i]);
    }
    curGraph_5 = ui->customPlot_5->addGraph();
    curGraph_5->setLineStyle(QCPGraph::lsNone);
    curGraph_5->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 2));
    ui->customPlot_5->plotLayout()->insertRow(0);
    m_title_5 = new QCPTextElement(ui->customPlot_5, "Re");
    ui->customPlot_5->plotLayout()->addElement(0, 0, m_title_5);
    curGraph_5->setData(x_5, y_5);
    // 为坐标轴添加标签
    //ui->customPlot->xAxis->setLabel("In-Phase");
    //ui->customPlot->yAxis->setLabel("Quadrature");
    // 设置坐标轴的范围，以看到所有数据
    ui->customPlot_5->graph(0)->rescaleAxes();
    ui->customPlot_5->legend->setVisible(false); // 显示图例
    ui->customPlot_5->replot();

    for (int i=0; i<EQ_ALL_ERR_LEN; i++)
    {
        x_6.append(i);
        y_6.append(mutiSignalDecode->EqSig_PriCh_Temp_Q[LOW][i]);
    }
    curGraph_6 = ui->customPlot_6->addGraph();
    curGraph_6->setLineStyle(QCPGraph::lsNone);
    curGraph_6->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 2));
    ui->customPlot_6->plotLayout()->insertRow(0);
    m_title_6 = new QCPTextElement(ui->customPlot_6, "Im");
    ui->customPlot_6->plotLayout()->addElement(0, 0, m_title_6);
    curGraph_6->setData(x_6, y_6);

    // 设置坐标轴的范围，以看到所有数据
    ui->customPlot_6->graph(0)->rescaleAxes();
    ui->customPlot_6->legend->setVisible(false); // 显示图例
    ui->customPlot_6->replot();

    for (int i=0; i<EQ_ALL_ERR_LEN; i++)
    {
        x_7.append(i);
        y_7.append(mutiSignalDecode->EqErr_PriCh_Temp[LOW][i]);
    }
    curGraph_7 = ui->customPlot_7->addGraph();
    curGraph_7->setLineStyle(QCPGraph::lsLine);
    ui->customPlot_7->graph(0)->setPen(QPen(Qt::magenta)); // 曲线的颜色
    ui->customPlot_7->plotLayout()->insertRow(0);
    m_title_7 = new QCPTextElement(ui->customPlot_7, "均衡后误差");
    ui->customPlot_7->plotLayout()->addElement(0, 0, m_title_7);
    curGraph_7->setData(x_7, y_7);
    // 为坐标轴添加标签
    //ui->customPlot->xAxis->setLabel("In-Phase");
    //ui->customPlot->yAxis->setLabel("Quadrature");
    // 设置坐标轴的范围，以看到所有数据
    ui->customPlot_7->graph(0)->rescaleAxes();
    ui->customPlot_7->legend->setVisible(false); // 显示图例
    ui->customPlot_7->replot();

    for (int i=0; i<MseqCorrOut_PriCh_TempSize; i++)
    {
        x_8.append(i);
        y_8.append(mutiSignalDecode->MseqCorrOut_PriCh_Temp[LOW][i]);
    }
    curGraph_8 = ui->customPlot_8->addGraph();
    curGraph_8->setLineStyle(QCPGraph::lsLine);
    ui->customPlot_8->graph(0)->setPen(QPen(Qt::magenta)); // 曲线的颜色
    ui->customPlot_8->plotLayout()->insertRow(0);
    m_title_8 = new QCPTextElement(ui->customPlot_8, "M序列相关");
    ui->customPlot_8->plotLayout()->addElement(0, 0, m_title_8);
    curGraph_8->setData(x_8, y_8);
    // 为坐标轴添加标签
    //ui->customPlot->xAxis->setLabel("In-Phase");
    //ui->customPlot->yAxis->setLabel("Quadrature");
    // 设置坐标轴的范围，以看到所有数据
    ui->customPlot_8->graph(0)->rescaleAxes();
    ui->customPlot_8->legend->setVisible(false); // 显示图例
    ui->customPlot_8->replot();

    ui->horizontalSlider->setRange(0,500);
    ui->horizontalSlider->setValue(250);

    //ui->groupBox->setVisible(false);

}

HistoryForm::~HistoryForm()
{
    delete ui;
}




//关闭窗口回到导航界面
void HistoryForm::closeEvent(QCloseEvent *e)
{
    //   nf->show();
    pause_status = 2;
}


void HistoryForm::FirFilter_2(double *b, int inputlength, double *x, QList<double> y)
{
    int i, j;
    y[0] = b[0] * x[0];
    for (i = 1; i < inputlength; i++)//对20个输入函数逐一处理
    {
        y[i] = 0.0;
        for (j = 0; j < 31; j++)
        {
            if (i >= j) {
                y[i] = y[i] + b[j] * x[i - j];
            }//分子系数与输入函数的乘积和
        }
    }
}


void HistoryForm::drawHighWaveformPlot()
{
    int type = 1;
    for (int i=0; i<EQ_ALL_ERR_LEN; i++)
    {
        x_1.replace(i,i);
        y_1.replace(i,mutiSignalDecode->EqSig_PriCh_Temp_I[type][i]);
    }
    curGraph_1->setData(x_1, y_1);
    ui->customPlot_1->graph(0)->rescaleAxes();
    // 重画图像
    ui->customPlot_1->replot();

    for (int i=0; i<EQ_ALL_ERR_LEN; i++)
    {
        x_2.replace(i,i);
        y_2.replace(i,mutiSignalDecode->EqSig_PriCh_Temp_Q[type][i]);
    }
    curGraph_2->setData(x_2, y_2);
    ui->customPlot_2->graph(0)->rescaleAxes();
    // 重画图像
    ui->customPlot_2->replot();

    for (int i=0; i<EQ_ALL_ERR_LEN; i++)
    {
        x_3.replace(i,i);
        y_3.replace(i,mutiSignalDecode->EqErr_PriCh_Temp[type][i]);
    }
    curGraph_3->setData(x_3, y_3);
    ui->customPlot_3->graph(0)->rescaleAxes();
    // 重画图像
    ui->customPlot_3->replot();

    for (int i=0; i<MseqCorrOut_PriCh_TempSize; i++)
    {
        x_4.replace(i,i);
        y_4.replace(i,mutiSignalDecode->MseqCorrOut_PriCh_Temp[type][i]);
    }
    curGraph_4->setData(x_4, y_4);
    ui->customPlot_4->graph(0)->rescaleAxes();
    // 重画图像
    ui->customPlot_4->replot();
}

void HistoryForm::drawLowWaveformPlot()
{
    int type = 0;
    for (int i=0; i<EQ_ALL_ERR_LEN; i++)
    {
        x_5.replace(i,i);
        y_5.replace(i,mutiSignalDecode->EqSig_PriCh_Temp_I[type][i]);
    }
    curGraph_5->setData(x_5, y_5);
    ui->customPlot_5->graph(0)->rescaleAxes();
    // 重画图像
    ui->customPlot_5->replot();

    for (int i=0; i<EQ_ALL_ERR_LEN; i++)
    {
        x_6.replace(i,i);
        y_6.replace(i,mutiSignalDecode->EqSig_PriCh_Temp_Q[type][i]);
    }
    curGraph_6->setData(x_6, y_6);
    ui->customPlot_6->graph(0)->rescaleAxes();
    // 重画图像
    ui->customPlot_6->replot();

    for (int i=0; i<EQ_ALL_ERR_LEN; i++)
    {
        x_7.replace(i,i);
        y_7.replace(i,mutiSignalDecode->EqErr_PriCh_Temp[type][i]);
    }
    curGraph_7->setData(x_7, y_7);
    ui->customPlot_7->graph(0)->rescaleAxes();
    // 重画图像
    ui->customPlot_7->replot();

    for (int i=0; i<MseqCorrOut_PriCh_TempSize; i++)
    {
        x_8.replace(i,i);
        y_8.replace(i,mutiSignalDecode->MseqCorrOut_PriCh_Temp[type][i]);
    }
    curGraph_8->setData(x_8, y_8);
    ui->customPlot_8->graph(0)->rescaleAxes();
    // 重画图像
    ui->customPlot_8->replot();
}

void HistoryForm::message_show(){
    // qDebug()<<"message_show()"<<endl;
    //    drawWaveformPlot();
    //    hf_1->drawWaveformPlot();
    //    hf_2->drawWaveformPlot();
}



void HistoryForm::on_pushButton_2_clicked()
{

    if(pause_status == 0){
        pause_status = 1;
        ui->pushButton_2->setText("恢复播放");
    }else{
        pause_status = 0;
        ui->pushButton_2->setText("暂停");
    }

}


/*
 * 将字符转换为数值
 * */
int c2i(char ch)
{
    // 如果是数字，则用数字的ASCII码减去48, 如果ch = ‘2‘ ,则 ‘2‘ - 48 = 2
    if(isdigit(ch))
        return ch - 48;

    // 如果是字母，但不是A~F,a~f则返回
    if( ch < 'A' || (ch > 'F' && ch < 'a') || ch > 'z' )
        return -1;

    // 如果是大写字母，则用数字的ASCII码减去55, 如果ch = ‘A‘ ,则 ‘A‘ - 55 = 10
    // 如果是小写字母，则用数字的ASCII码减去87, 如果ch = ‘a‘ ,则 ‘a‘ - 87 = 10
    if(isalpha(ch))
        return isupper(ch) ? ch - 55 : ch - 87;

    return -1;
}

void setFilePos(FILE *stream,int curPos){
    fseek(stream,curPos,SEEK_SET);
}

int totoalSize(FILE *stream){
    int curPos,length;

    curPos = ftell(stream);
    fseek(stream,0L,SEEK_END);
    length = ftell(stream);
    fseek(stream,curPos,SEEK_SET);

    return length;
}


void HistoryForm::on_pushButton_3_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,QStringLiteral("文件对话框！"),"F:",QStringLiteral("文本文件(*txt)"));

    QTextCodec *code = QTextCodec::codecForName("gb2312");
    std::string stdStr = code->fromUnicode(fileName).data();
    char const* save_url_ = stdStr.c_str();
    if(fp != NULL){
        fclose(fp);
    }
    fp = fopen(save_url_, "r");
    ui->horizontalSlider_2->setRange(0,totoalSize(fp));

    DataAnalysis();

}


void HistoryForm::showSignalInfo(double singnal,int hzType){
    QString strSig = QString::number(singnal,'f', 3);
    if(hzType == 1){
        ui->labelXZB->setText("信噪比 = "+ strSig);
    }else{
        ui->labelXZB_2->setText("信噪比 = "+ strSig);
    }

}


void HistoryForm::DataAnalysis(){
    FILE *fp1;
    QTextCodec *code = QTextCodec::codecForName("gb2312");
    if(mutiSignalDecode->save_source_data[HIGH]>0){
        QString save_url1 = mutiSignalDecode->baseUrl + "/source/High.txt";
        std::string stdStr1 = code->fromUnicode(save_url1).data();
        char const* save_url_1 = stdStr1.c_str();
        fp1 = fopen(save_url_1, "a+");
    }

    int j=0,hzType=0;
    mutiSignalDecode->frame_counter = 0;


    char buffer[12];
    memset(buffer,0x0,20);

    playStatus = 1;
    while(fgets(buffer, 20, fp)){
        QCoreApplication::processEvents();

        if(currIndex != ui->horizontalSlider_2->value()){
            currIndex = ui->horizontalSlider_2->value();
            fseek(fp,currIndex,SEEK_SET);
        }



        double b10dec = 0x0;
        double temp1,temp2,temp3,temp4;

        temp1 = c2i(buffer[0])*10+c2i(buffer[1]);
        temp2 = c2i(buffer[3])*10+c2i(buffer[4]);
        temp3 = c2i(buffer[6])*10+c2i(buffer[7]);
        temp4 = c2i(buffer[9])*10+c2i(buffer[10]);


        b10dec = (temp1*256.0 + temp2) / 65536.0 * 2.5 - 1.25;
        b10dec = b10dec*mutiSignalDecode->ZoomIn[LOW];

        mutiSignalDecode->MudSigStand[LOW]->Pri[j] = b10dec;



        if(mutiSignalDecode->DemodParam[0]->Demodule_Mode == 153){ //0x99 psk_psk

            b10dec = (temp3*256.0 + temp4) / 65536.0 * 2.5 - 1.25;
            b10dec = b10dec*mutiSignalDecode->ZoomIn[HIGH];
            mutiSignalDecode->MudSigStand[HIGH]->Pri[j] = b10dec;
               fprintf(fp1,"%.12f\n",b10dec);
        }
        memset(buffer,0x0,20);
        j++;
        if(j == mutiSignalDecode->DemodParam[0]->PreSignal_Len){
            mutiSignalDecode->frame_counter++;
            j = 0;
            currIndex = ftell(fp);
            ui->horizontalSlider_2->setValue(currIndex);            
            //解调低频数据
            hzType = LOW;

            if(mutiSignalDecode->DemodParam[0]->Demodule_Mode == 152){ //0x98 dbpsk
                mutiSignalDecode->dbpsk_demodule(hzType);
            }else{
                mutiSignalDecode->demodule(hzType); //开始解调
            }
            drawLowWaveformPlot();

            if(!df->isHidden()){
                df->drawLowWaveformPlot();

            }
            if(!hf_1->isHidden()){

                hf_1->drawLowWaveformPlot();

            }
            if(!hf_2->isHidden()){
                hf_2->drawWaveformPlot(hzType);
            }



            if(mutiSignalDecode->DemodParam[0]->Demodule_Mode == 153){ //0x99 psk_psk
                //解调高频数据
                hzType = HIGH;
                mutiSignalDecode->demodule(hzType); //开始解调
                drawHighWaveformPlot();
                if(!df->isHidden()){
                    df->drawHighWaveformPlot();
                }
                if(!hf_1->isHidden()){
                    hf_1->drawHighWaveformPlot();
                }
                if(!hf_2->isHidden()){
                    hf_2->drawWaveformPlot(hzType);
                }

            }


            QTimer timer;
            timer.setTimerType(Qt::PreciseTimer);
            int speed = 500-ui->horizontalSlider->value();
            timer.start(speed);

            while(timer.remainingTime() > 0 || pause_status == 1){
                QCoreApplication::processEvents();
            }
            if(pause_status == 2){
                break;
            }

        }

    }
    fclose(fp1);
    playStatus = 2;
}


void HistoryForm::on_horizontalSlider_2_actionTriggered(int action)
{
    if(playStatus == 2){
        currIndex = ui->horizontalSlider_2->value();
        fseek(fp,currIndex,SEEK_SET);
        DataAnalysis();
    }
}
